package cn.lx.util;


import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Range;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class WordUtils {

    /**
     * 加载读取Word文件格式doc
     *
     * @param filePath 文件路径
     * @return 文件类型
     */
    public static void loadReadDoc(String filePath) {
        File file = new File(filePath);
        try {
            FileInputStream fis = new FileInputStream(file);
            HWPFDocument doc = new HWPFDocument(fis);
            String doc1 = doc.getDocumentText();
            System.out.println(doc1);
            StringBuilder doc2 = doc.getText();
            System.out.println(doc2);
            Range rang = doc.getRange();
            String doc3 = rang.text();
            System.out.println(doc3);
            fis.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 加载读取Word文件格式docx
     *
     * @param filePath 文件路径
     * @return 文件类型
     */
    public static void loadReadDocx(String filePath) throws IOException {
        File file = new File(filePath);
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(file);
            XWPFDocument xdoc = new XWPFDocument(fis);
            XWPFWordExtractor extractor = new XWPFWordExtractor(xdoc);
            String doc1 = extractor.getText();
            System.out.println(doc1);
            fis.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            fis.close();
        }
    }

    /**
     * 加载读取文件
     *
     * @param filePath 文件路径
     * @return 文件类型
     */
    public static void loadRead(String filePath) throws IOException {

        // 获取文件类型
        String fileType = FileUtils.getType(filePath).toString();
        System.out.println(fileType);
        // todo 校验文件类型
        // todo 校验文件内容是否为空

        loadReadDocx(filePath);

    }


    public static void main(String[] args) throws IOException {
        String s = "/Users/lixin/Downloads/题库第二部分.docx";
        loadRead(s);
    }


}
